package com.yuji.aacar.controller.address;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.ImageView;

import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseActivity;
import com.yuji.aacar.base.Const;
import com.yuji.aacar.base.EventConst;
import com.yuji.aacar.base.UserCenter;
import com.yuji.aacar.bean.beans.QueryCarAddressInfo;
import com.yuji.aacar.bean.response.LoginResponse;
import com.yuji.aacar.bean.response.ManagerCarAddressResponse;
import com.yuji.aacar.bean.response.QueryCarAddressResponse;
import com.yuji.aacar.controller.adapter.AddressAdapter;
import com.yuji.aacar.controller.address.newaddress.NewAddressActivity;
import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.service.BaseServiceParams;
import com.yuji.aacar.widgets.autolayout.AutoRelativeLayout;
import com.yuji.aacar.widgets.pulltorefresh.PtrFrameLayout;
import com.yuji.aacar.widgets.pulltorefresh.core.PtrDefaultHandler2;
import com.yuji.aacar.widgets.pulltorefresh.core.WptrClassicFrameLayout;
import com.yuji.aacar.widgets.textview.PingFangTextView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.yuji.aacar.base.UserCenter.getCurrentUser;

/**
 * <li>Package:com.yuji.aacar.controller.address</li>
 * <li>Author: lining </li>
 * <li>Date: 2018/3/6</li>
 * <li>Description:   </li>
 */

public class AddressActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.back_image)
    AutoRelativeLayout backImage;
    @BindView(R.id.title_content)
    PingFangTextView titleContent;
    @BindView(R.id.back_login)
    PingFangTextView backLogin;
    @BindView(R.id.title_message_iv)
    ImageView titleMessageIv;
    @BindView(R.id.title_message_rl)
    AutoRelativeLayout titleMessageRl;
    @BindView(R.id.title_rl)
    AutoRelativeLayout titleRl;
    @BindView(R.id.address_add_btn_layout)
    AutoRelativeLayout addressAddBtnLayout;
    @BindView(R.id.layout_recyclerview)
    RecyclerView layoutRecyclerview;
    @BindView(R.id.layout_pull_to_refresh)
    WptrClassicFrameLayout layoutPullToRefresh;
    @BindView(R.id.address_add_btn)
    Button addressAddBtn;


    private ArrayList<QueryCarAddressInfo> datas;
    private AddressAdapter adapter;
    private QueryCarAddressInfo addressInfo;
    private QueryCarAddressInfo deleteAddressInfo;
    private String isDefaultAddress = "0";
    private String fromPage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_address);
        ButterKnife.bind(this);
        initTitle(true, "洗车地址管理", null);
        super.onCreate(savedInstanceState);
        fromPage = getIntent().getStringExtra("from");
        initData();
        initList();
    }

    @Override
    public void onResume() {
        super.onResume();
        request();
    }

    private void initList() {
        layoutPullToRefresh.setPullToRefresh(true);
        //阻力系数，阻力越大，能拉动范围越小，默认为1.7f
        layoutPullToRefresh.setResistance(1.7f);
        //系数越大，需拉动越大的距离才能刷新或加载，默认1.2f
        layoutPullToRefresh.setRatioOfHeaderHeightToRefresh(1.2f);
        layoutPullToRefresh.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                layoutPullToRefresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        layoutPullToRefresh.refreshComplete();
                    }
                }, 2000);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                request();
            }
        });
        layoutPullToRefresh.setMode(PtrFrameLayout.Mode.REFRESH);


        initData();
        adapter = new AddressAdapter(AddressActivity.this, datas);

        layoutRecyclerview.setLayoutManager(new LinearLayoutManager(AddressActivity.this));
        layoutRecyclerview.setAdapter(adapter);
//        layoutRecyclerview.addOnItemTouchListener(new RecyclerViewItemTouchListener(layoutRecyclerview, new RecyclerViewItemTouchListener.OnItemClickListener() {
//
//            @Override
//            public void onItemClick(View view) {
//                AddressAdapter.ViewHolder holder = (AddressAdapter.ViewHolder) layoutRecyclerview.getChildViewHolder(view);
//                int position = layoutRecyclerview.getChildViewHolder(view).getPosition();
//                LogUtil.e("position--", position);
//                QueryCarAddressInfo addressInfo = datas.get(position);
//                LoginResponse user = UserCenter.getCurrentUser();
//                if (null != user) {
//                    String userId = user.getMemberId();
//                    UserCenter.setDefaultAddress(userId, addressInfo);
//                    CoreEventCenter.postObject(EventConst.SELECT_ADDRESS_OVER, addressInfo);
//                    finish();
//                }
//            }
//
//            @Override
//            public void onItemLongClick(View view) {
//
//            }
//        }));
    }

    @Override
    public void alreadyBindBaseViewModel() {
        super.alreadyBindBaseViewModel();

    }

    private void request() {
        requestParams = BaseServiceParams.queryCarAddress("1000", "0");
        doTask(BaseServiceMediator.QUERY_CAR_ADDRESS);
    }

    private void request2() {
        //        requestParams = BaseServiceParams.managerCarAddress(
        //                tagStr,selectedRoom.getAreaCode(),
        //                selectedRoom.getAreaName(), selectedRoom.getCityCode(),
        //                selectedRoom.getCityName(),contectName,
        //                contectNo,addressDetail, "0","3", contectNo,selectedRoom.getProvinceCode(),selectedRoom.getProvinceName());
        //        doTask(BaseServiceMediator.MANAGER_CAR_ADDRESS);

    }

    private void initData() {
        datas = new ArrayList<>();
    }


    @Override
    public void requestSuccess(CoreServiceResponse response) {
        super.requestSuccess(response);
        if (response.getRequestCode() == BaseServiceMediator.QUERY_CAR_ADDRESS_CODE) {
            QueryCarAddressResponse queryCarAddressResponse = (QueryCarAddressResponse) response.getResponse();
            datas = queryCarAddressResponse.getInfo();
            adapter.setDatas(datas);
            adapter.notifyDataSetChanged();
            layoutPullToRefresh.refreshComplete();
        } else if (response.getRequestCode() == BaseServiceMediator.MANGE_CAR_ADDRESS_DELETE) {
            ManagerCarAddressResponse carAddressResponse = (ManagerCarAddressResponse) response.getResponse();
            if (carAddressResponse.isSuccess()) {
                if (null != deleteAddressInfo && deleteAddressInfo.getIsDefault().contentEquals("1")){
                    LoginResponse user = UserCenter.getCurrentUser();
                    if (null != user){
                        UserCenter.setDefaultAddress(user.getMemberId(),null);
                    }
                }
                request();
            }
        } else if (response.getRequestCode() == BaseServiceMediator.MANGE_CAR_ADDRESS_MODIFY) {
            ManagerCarAddressResponse carAddressResponse = (ManagerCarAddressResponse) response.getResponse();
            if (carAddressResponse.isSuccess()) {
                LoginResponse user = getCurrentUser();
                if (null != user) {
                    if (isDefaultAddress.contentEquals("1")) {
                        UserCenter.setDefaultAddress(user.getMemberId(), addressInfo);
                    } else {
                        UserCenter.setDefaultAddress(user.getMemberId(), null);
                    }

                }
                request();
            }
        }
    }

    @Override
    public void handleMessage(CoreEventBusMessage message) {
        super.handleMessage(message);
        if (message.getMessageCode().contentEquals(EventConst.CAR_MANAGE_DELETE + "")) {
            DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int position = Integer.parseInt(message.getMessage());
                    deleteAddressInfo = datas.get(position);
                    requestParams = BaseServiceParams.managerCarAddress(
                            deleteAddressInfo.getAddrType(), deleteAddressInfo.getAreaCode(),
                            deleteAddressInfo.getAreaName(), deleteAddressInfo.getCityCode(),
                            deleteAddressInfo.getCityName(), deleteAddressInfo.getUserName(),
                            deleteAddressInfo.getPhoneNo(), deleteAddressInfo.getDetailAddress(),
                            deleteAddressInfo.getIsDefault(), "3", deleteAddressInfo.getPhoneNo(), "", "",
                            deleteAddressInfo.getRoomName(), deleteAddressInfo.getRoomCode(), deleteAddressInfo.getPid());
                    doTask(BaseServiceMediator.MANAGER_CAR_ADDRESS_DELETE);
                }
            };
            showAlertDialogue("取消", "提示", "确认删除？", "确认", clickListener);
        } else if (message.getMessageCode().contentEquals(EventConst.CAR_MANAGE_EDIT + "")) {

            DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int position = Integer.parseInt(message.getMessage());
                    QueryCarAddressInfo queryCarAddressInfo = datas.get(position);
                    presentController(NewAddressActivity.class, getIntent().putExtra("QueryCarAddressInfo", queryCarAddressInfo), Const.EDIT_RESULT_CODE);
                }
            };
            showAlertDialogue("取消", "提示", "需要编辑？", "确认", clickListener);
        } else if (message.getMessageCode().contentEquals(EventConst.CAR_MANAGE_DEFAULT + "")) {
            String[] str = message.getMessage().split(":");
            int position = Integer.parseInt(str[0]);
            isDefaultAddress = str[1];
            addressInfo = datas.get(position);
            requestParams = BaseServiceParams.managerCarAddress(
                    addressInfo.getAddrType(), addressInfo.getAreaCode(),
                    addressInfo.getAreaName(), addressInfo.getCityCode(),
                    addressInfo.getCityName(), addressInfo.getUserName(),
                    addressInfo.getPhoneNo(), addressInfo.getDetailAddress(),
                    isDefaultAddress, "2", addressInfo.getPhoneNo(), addressInfo.getProvinceCode(), addressInfo.getProvinceName(),
                    addressInfo.getRoomName(), addressInfo.getRoomCode(), addressInfo.getPid());
            doTask(BaseServiceMediator.MANAGER_CAR_ADDRESS_EDIT);
        } else if (message.getMessageCode().contentEquals(EventConst.FIRST_DEFAULT_ADDRESS_FINISH + "")) {
            if (null != fromPage && fromPage.contentEquals(Const.FROM_WRITE_ORDER)){
                finish();
            }
        } else if (message.getMessageCode().contentEquals(EventConst.SELECT_ADDRESS_OVER + "")){
            if (null != fromPage && fromPage.contentEquals(Const.FROM_WRITE_ORDER)){
                finish();
            }
        }
    }


    @OnClick(R.id.address_add_btn)
    public void onClick() {
        //        requestParams = BaseServiceParams.queryCarAddress("30", "0");
        //        doTask(BaseServiceMediator.QUERY_CAR_ADDRESS);
        presentController(NewAddressActivity.class, Const.ADD_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == Const.ADD_RESULT_CODE) {
            request();
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    private void setDefaultAddressRequest(String flag) {

    }
}
